import { FileSearchOutlined } from '@ant-design/icons';
import { OperationlogsResponse } from 'admin/schema/OperationLog';
import {
  createCallIntentionReportDownloadTask,
  createCheckAvaluateReportDownloadTask,
  getCallIntentionReportList,
} from 'admin/servers/servers';
import { Button, ConfigProvider, Form, message, Space, Table } from 'antd';
import { FetchDataParam, FetchDataResponse, PageSelect } from 'components/UILibrary/pageSelect';
import { checkPermission } from 'permission/Index';
import React, { Component } from 'react';
import { taskscanceldatapermission } from 'seats/servers/servers';
import { clearNull, transformTableData } from 'utils/tools';
import './style.scss';

interface Props {}
interface State {}

/**
 * 通话意图报表
 *
 * @export
 * @class CallIntentionReport
 * @extends {Component<Props, State>}
 */
export default class CallIntentionReport extends Component<Props, State> {
  taskNameRef = React.createRef<any>();
  state = {
    taskId: undefined,
    pageInfo: {
      pageTotal: 0,
      pageNum: 1,
      pageSize: 10,
    },
    tableData: [],
    tableTit: [],
    tableLoading: false,
  };
  componentDidMount() {}
  componentWillUnmount() {
    this.setState = (state, callback) => {
      return;
    };
  }

  /**
   * 查询table数据
   */
  private async fetchList() {
    const { taskId, pageInfo } = this.state;
    if (!taskId) {
      message.warning('请先选择任务');
      return;
    }
    this.setState({
      tableLoading: true,
    });
    try {
      const res = await getCallIntentionReportList(
        clearNull({
          taskId,
          pageNo: pageInfo.pageNum,
          pageSize: pageInfo.pageSize,
        })
      );
      console.log('通话意图报表--原始数据', res.data);
      const arr: any = transformTableData(res.data);
      arr[0].unshift({
        title: '序号',
        dataIndex: 'index',
        key: 'index',
      });
      for (let i = 0; i < arr[1].length; i++) {
        arr[1][i].index = i + 1 + pageInfo.pageSize * (pageInfo.pageNum - 1);
      }
      console.log(arr[1], 'list加入index后');
      pageInfo.pageTotal = res.count as number;
      this.setState({
        tableTit: arr[0],
        tableData: arr[1],
        pageInfo: pageInfo,
      });
    } catch (error) {
      console.error(`系统异常: ${JSON.stringify(error)}`);
    }
    this.setState({
      tableLoading: false,
    });
  }

  /**
   * 表格行操作后，重置列表
   */
  private resetList() {
    this.jumpPage(1);
  }
  /**
   * 跳页方法
   */
  private jumpPage(pageNum: number, pageSize?: number): void {
    const newProp = this.state.pageInfo;
    newProp.pageNum = pageNum;
    if (pageSize) {
      newProp.pageSize = pageSize;
    }
    this.setState(
      {
        pageInfo: newProp,
      },
      () => {
        this.fetchList();
      }
    );
  }

  /**创建下载任务*/
  private handleExport(): void {
    const { taskId } = this.state;
    if (!taskId) {
      message.warning('请先选择任务');
      return;
    }
    const postData = clearNull({
      taskId,
      type: 0,
    });
    createCallIntentionReportDownloadTask(postData as any).then(res => {
      if (res.code === 0) {
        // 创建下载任务
        message.warning('数据正在准备中，请稍候到下载管理中下载');
      } else {
        message.error(`${res.tips}(错误码:${res.code})`);
      }
    });
  }

  /**创建下载任务*/
  private handleExport2(): void {
    const { taskId } = this.state;
    if (!taskId) {
      message.warning('请先选择任务');
      return;
    }
    const postData = clearNull({
      taskId,
      type: 1,
    });
    createCheckAvaluateReportDownloadTask(postData as any).then(res => {
      if (res.code === 0) {
        // 创建下载任务
        message.warning('数据正在准备中，请稍候到下载管理中下载');
      } else {
        message.error(`${res.tips}(错误码:${res.code})`);
      }
    });
  }
  /**
   * 重置搜索列表
   */
  private resetSearch() {
    // 重置搜索条件；重置列表
    this.taskNameRef.current.clear();
    this.setState({
      taskId: undefined,
      pageInfo: {
        pageTotal: 0,
        pageNum: 1,
        pageSize: 10,
      },
      tableData: [],
      tableTit: [],
    });
  }

  /**
   * 获取企业下任务列表
   * flowType：机器人任务-0，人机协同任务-2
   */
  private fetchTaskList = (args: FetchDataParam): FetchDataResponse => {
    return new Promise(resolve => {
      taskscanceldatapermission({
        pageNo: args.pageNum,
        pageSize: args.pageSize,
        taskName: args.keywords,
        flowType: [0, 2],
      })
        .then(res => {
          resolve({
            data: res.data?.map((item: any) => {
              return {
                label: item.taskName,
                value: item.taskId,
              };
            }),
            total: res.count as number,
          });
        })
        .catch(error => {
          console.error(`系统异常: ${JSON.stringify(error)}`);
        });
    });
  };
  /**
   * 处理操作类型变更
   */
  private onTaskNameChange = (val: any): void => {
    this.setState({
      taskId: val,
    });
  };

  render() {
    const {
      taskNameRef,
      state: {
        tableTit,
        tableData,
        pageInfo: { pageNum, pageSize, pageTotal },
        tableLoading,
      },
    } = this;
    /**
     * 自定义table空状态
     */
    const customizeRenderEmpty = () => (
      <div style={{ textAlign: 'center' }}>
        <FileSearchOutlined style={{ fontSize: 104, margin: 20, color: '#d9d9d9' }} />
        <p style={{ color: '#5e6871' }}>请先选择任务</p>
      </div>
    );
    return (
      <>
        <div className="mgr-header call-intention-header">
          <div className="mgr-header-left">
            <Form layout="inline">
              <Form.Item label="任务名称" style={{ width: 400 }}>
                <PageSelect
                  ref={taskNameRef}
                  fetchData={this.fetchTaskList}
                  onChange={this.onTaskNameChange as any}
                  placeholder="请选择任务名称"
                />
              </Form.Item>
              <Space size="middle">
                <Button
                  type="primary"
                  onClick={() => {
                    this.resetList();
                  }}
                >
                  搜索
                </Button>
                <Button
                  type="primary"
                  ghost
                  onClick={() => {
                    this.resetSearch();
                  }}
                >
                  重置
                </Button>
              </Space>
            </Form>
          </div>
          <div className="mgr-header-right">
            {checkPermission('/report/callIntention/export') && (
              <Button
                type="primary"
                onClick={() => {
                  this.handleExport();
                }}
              >
                导出
              </Button>
            )}
          </div>
          <div className="mgr-header-right">
            {checkPermission('/report/callIntention/export') && (
              <Button
                type="primary"
                onClick={() => {
                  this.handleExport2();
                }}
              >
                导出为集团测评报表
              </Button>
            )}
          </div>
        </div>
        <div className="mgr-table">
          <ConfigProvider
            renderEmpty={!tableLoading && tableTit.length ? undefined : customizeRenderEmpty}
          >
            <Table
              loading={tableLoading}
              dataSource={tableData}
              scroll={{ x: 'max-content' }}
              columns={tableTit as any}
              rowKey={(record: OperationlogsResponse[0], index) =>
                `table${record.userName}${index}`
              }
              pagination={{
                showSizeChanger: true,
                total: pageTotal,
                showTotal: total => `共 ${total} 条`,
                current: pageNum,
                pageSize: pageSize,
                onChange: (pageNum, pageSize) => {
                  this.jumpPage(pageNum, pageSize as number);
                },
              }}
            />
          </ConfigProvider>
        </div>
      </>
    );
  }
}
